<template>
  <div class="course-container mx-center">
    <!-- 搜索模块 -->
    <div class="course-search">
      <div class="search-tag">
        文章管理
      </div>
      <div class="search-wrapper">
        <input v-model="query.title" @keyup.enter="fetchData" type="text" placeholder="输入文章内容搜索">
        <i @click="fetchData" class="iconfont">&#xe63c;</i>
      </div>
      <el-button v-if="userInfo.identity == 'vip'" @click="handleCreate" style="float: right;margin: 18px;" type="primary" size="mini">添加</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      size="mini"
      highlight-current-row
    >
      <el-table-column label="标题">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="封面" width="130" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.img" width="100px" height="60px">
        </template>
      </el-table-column>
      <el-table-column label="作者" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center">
        <template slot-scope="scope">
          <el-tag type="primary" size="mini" v-for="tag in scope.row.tags.split(',')">{{tag}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="140" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-if="userInfo.identity == 'vip'" type="primary" size="mini" @click="handleUpdate(row.id)">
            编辑
          </el-button>
          <el-button size="mini" type="warning" @click="handleDel(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="fetchData"/>

    <el-dialog title="修改/新增" :visible.sync="dialogVisible" width="60%" :append-to-body='true' :close-on-click-modal="false" :show-close="false"
               :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="文章标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="文章类型" style="width: 48%;display: inline-block">
          <el-select v-model="form.type" style="width: 100%" placeholder="请选择">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签" style="width: 48%;display: inline-block">
          <el-tag
            :key="tag"
            v-for="tag in tags"
            closable
            :disable-transitions="false"
            @close="handleTagsClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </el-form-item>
        <el-form-item label="文章内容">
          <markdown-editor ref="markdownEditor" :content="form.contentMd" @editor="editor" height="600px"></markdown-editor>
        </el-form-item>
        <el-form-item label="文章封面" style="width: 30%;display: inline-block">
          <el-upload
            class="avatar-uploader"
            action="/api/storage/anon/upload"
            name="file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imgUrl" :src="imgUrl"  style="width: 178px;height: 178px;display: block">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章描述" style="width: 65%;display: inline-block;float: right">
          <el-input type="textarea" v-model="form.des"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAction">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {getArticleList, getArticleDetail, addArticle, delArticle, updateArticle} from '@/api/article.js'
  import Pagination from 'components/pagination/pagination.vue'
  import {ERR_OK} from "@/api/config";
  import MarkdownEditor from './components/markdown'

  export default {
    components: {Pagination, MarkdownEditor},
    data () {
      return {
        list: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        },
        total: 0,
        query: {},
        form: {},
        inputVisible: false,
        inputValue: '',
        tags: [],
        imgUrl: '',
        typeOptions: [
          {
            value: 'vip',
          },
          {
            value: '免费',
          },
        ],
        dialogVisible: false
      }
    },
    created () {
      //判断当前用户身份
      //如果是管理员，就加载所有；如果不是就加载属于自己的部分
      if (this.userInfo.identity != '管理员') {
        this.query.uid = this.userInfo.id;
      }
      this.fetchData()
    },
    computed: {
      // vuex
      ...mapGetters(['userInfo'])
    },
    methods: {
      handleClose() {
        this.form = {}
        this.tags = []
        this.inputValue = ''
        this.imgUrl = ''
        this.dialogVisible = false
      },
      fetchData () {
        this.listLoading = true
        getArticleList(this.query, this.listQuery).then(response => {
          this.list = response.data.rows
          this.listLoading = false
          this.total = response.data.total
        })
      },
      //markdown编辑器数据变化时触发
      editor(val){
        this.form.contentMd = val.md;
        this.form.content = val.html;
      },
      submitAction() {
        this.form.tags = this.tags.toString()
        if (this.form.id == undefined) {
          // 新增
          addArticle(this.form).then(res => {
            this.$message.success('添加成功')
            this.fetchData()
          })
        } else {
          // 更新
          updateArticle(this.form).then(res => {
            this.$message.success('修改成功')
            this.fetchData()
          })
        }
        this.fetchData()
        this.dialogVisible = false
        this.handleClose()
      },
      handleCreate () {
        this.dialogVisible = true
      },
      handleUpdate (id) {
        getArticleDetail(id).then(res => {
          if (res.code == ERR_OK) {
            this.form = res.data
            this.tags = res.data.tags.split(',')
            this.imgUrl = res.data.img
            this.dialogVisible = true
          }
        })
      },
      handleDel (id) {
        this.$confirm('你确定永久删除此条记录？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          delArticle(id).then(res => {
            this.$message.success('删除成功')
            this.fetchData();
          });
        }).catch(() => {
          this.$message.info('已取消删除')
        });
      },
      handleTagsClose(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      handleAvatarSuccess(res, file) {
        if (res.code == ERR_OK) {
          this.$message.success('上传成功')
          this.form.img = res.data.url
          this.imgUrl = res.data.url
        }
      },
    }
  }
</script>
<style lang="css">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
</style>
<style lang="stylus" scoped>
  @import '~assets/stylus/variables.styl';
  .course-container
    padding-top: 20px;
    .course-search
      padding: 12px 0;
      height: 60;
      .search-tag
        padding: 18px;
        font-size: 22px;
        display: inline-block;
        & > img:nth-child(2)
          margin-left: 16px;
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  .search-wrapper
    position: relative;
    float: right;
    width: 466px;
    height: 60px;
    line-height: 60px;
    .iconfont
      position: absolute;
      right: 15px;
      top: 20px;
      font-size: 24px;
      color: $font-four-color;
      cursor: pointer;
      line-height: 1;
    input
      padding: 0 16px;
      width: 100%;
      height: 36px;
      box-sizing: border-box;
      line-height: 36px;
      border-radius: 5px;
      outline: none;
      background: #f3f5f6;
      font-size: 14px;
      color: $font-first-color;
    .search-result
      z-index: 99;
      position: absolute;
      left: 0;
      top: 52px;
      right: 0;
      background-color: #fff;
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      box-shadow: 0 4px 8px 0px $shadow;
      .result-item
        padding-left: 20px;
        line-height: 50px;
        color: $font-first-color;
        cursor: pointer;
        font-size: 14px;
        &:hover
          background: #f3f5f6;
</style>
